package com.gbase8c.dmt.dao.file;

import com.gbase8c.dmt.common.util.JsonMapper;
import com.gbase8c.dmt.config.DmtConfig;
import com.gbase8c.dmt.dao.DboDao;

import com.gbase8c.dmt.model.migration.dto.DboDto;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public class DboDaoImpl extends BasicDao<DboDto> implements DboDao {

    private DmtConfig dmtConfig;

    public DboDaoImpl(DmtConfig dmtConfig) {
        super();
        this.dmtConfig = dmtConfig;
        mkdirs(path());
    }

    @Override
    public String path() {
        return dmtConfig.taskDir() + File.separator + "dbo";
    }

    @Override
    public File file(DboDto dboDto) {
        String filepath = StringUtils.join(new String[] {path(), dboDto.getId() + ".json"}, File.separator);
        return new File(filepath);
    }

    @Override
    public void preSave(String id, DboDto dboDto) {
    }

    @Override
    public void delete(DboDto dboDto) {
        delete(dboDto.getId());
    }

    public DboDto save(DboDto dto) {
        dto.setId(dto.getTask().getId());
        JsonMapper jsonMapper = JsonMapper.nonEmptyMapper();
        jsonMapper.toFile(file(dto.getId()), dto);
        return dto;
    }

}